package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.acticle.query.TravelQuery;
import cn.wolfcode.luowowo.acticle.service.IStrategyCommendService;
import cn.wolfcode.luowowo.acticle.service.ITravelCommendService;
import cn.wolfcode.luowowo.acticle.service.ITravelService;
import cn.wolfcode.luowowo.cache.key.RedisKeys;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.web.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class IndexController{

    @Reference
    private IUserInfoRedisService userInfoRedisService;
    @Reference
    private ITravelCommendService travelCommendService;
    @Reference
    private IStrategyCommendService strategyCommendService;
    @Reference
    private ITravelService travelService;

    @RequestMapping("")
    public String index(HttpServletRequest req,HttpServletResponse resp,Model model){
        //通过cookie拿到token
        String token = CookieUtil.getToken(req, resp);
        //拿到当前登录的用户
        UserInfo user = userInfoRedisService.getUserByToken(token);
        //使用session将用户信息返回给前端页面
        req.getSession().setAttribute("userInfo",user);
        //游记推荐5条
        model.addAttribute("tcs",travelCommendService.getTop5());
        //攻略推荐一条
        model.addAttribute("sc",strategyCommendService.getTop5().get(0));

        return "index/index";
    }

    @RequestMapping("/index/travelPage")
    public String travelPage(Model model, @ModelAttribute("qo")TravelQuery qo){
        model.addAttribute("pageInfo",travelService.query(qo));
        return "index/travelPageTpl";
    }


    @RequestMapping("save")
    @ResponseBody
    public Object save(UserInfo userInfo){
        return userInfo;
    }

    @RequestMapping("info")
    @ResponseBody
    public Object info(@UserParam UserInfo userInfo){
        return userInfo;
    }
    @RequestMapping("loginout")
    public String loginout(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        //删除cookie
        String token = CookieUtil.getToken(request, response);
        CookieUtil.addCookie("token",token,response,0);
        //删除session
        session.invalidate();
        //删除redis
        userInfoRedisService.deleteRedisByUserInfo(RedisKeys.USER_INFO_LOGIN.join(token));
        return "redirect:/login.html";
    }
}
